/**
 * 
 */
package com.jfinal.ext.kit;

import java.sql.Connection;
import java.sql.SQLException;

import com.jfinal.plugin.activerecord.DbKit;

/**
 * 手动控制事务
 * @author y.z
 */
public class Tx {
	private Connection conn=null;
	
	/**
	 * 开启事务
	 */
	public void open(){
		try {
			conn=DbKit.getConfig().getDataSource().getConnection();
            DbKit.getConfig().setThreadLocalConnection(conn);
            conn.setAutoCommit(false);//自动提交变成false
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 提交事务
	 */
	public void commit(){
		if(null != conn){
			try {
				conn.commit();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 回滚
	 */
	public void rollback(){
		try
        {
            if (null!=conn) conn.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
		
	}
	
	/**
	 * 关闭
	 */
	public void close(){
		 try
         {
             if (null!=conn) {
                 conn.close();
             }
         } catch (Exception e2) {
             e2.printStackTrace();
         } finally {
             DbKit.getConfig().removeThreadLocalConnection();
         }
	}
}
